
const app = getApp();
let livePlayer;
Component({
  properties: {
    'pullRefresh':{
      type: Boolean,
      observer: 'pullRefresh'
    },
    'tempid': {
      type: String,
      observer: ''
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    isShowFormat:false
  },
  /**
   * 组件的方法列表
   */
  ready: function () {
    var that = this;
    that.setData({
      sessionForm: app.globalData.sessionForm ? app.globalData.sessionForm:''
    })
    that.requestVrurl();
    that.requestIndex();
    app.contactData(that); 
  },
  methods: {
    // 客服回复组件间传值
    getreplyData: function (e) {
      var that = this;
      that.setData(e.detail);
    },
    pullRefresh:function(){
      var that = this;
      that.requestVrurl();
      that.requestIndex();
    }, 
    requestIndex: function () {
      var that = this;
      var data = {
        map: 'applet_custom_tpl_base',
        tplId: that.data.tempid ? that.data.tempid : ''
      };
      console.log(data);
      wx.showLoading({
        title: '加载中',
      })
      wx.request({
        url: app.globalData.requestUrl,
        data: data,
        success: function (res) {
          console.log(res.data);
          if (res.data.ec == 200) {
            var indexInfo = res.data.data;
            //初始化分类列表
            for (let i = 0; i < indexInfo.templateData.length; i++) {
              if (indexInfo.templateData[i].type == "seckill") { //秒杀组件
                indexInfo.templateData[i].curSort = 0;
                console.log('秒杀模板数据', indexInfo.templateData[i].curSort);
              }
              if (indexInfo.templateData[i].type =='catelist'){
                indexInfo.templateData[i].modelShow=false;
                indexInfo.templateData[i].categoryId = '';
              }
            }
            that.setData({
              headerTitle: indexInfo.headerTitle,
              pagebgColor: indexInfo.pagebgColor,
              componentData: indexInfo.templateData,
              isPullDownRefresh:false
            })
            if (that.data.headerTitle) {
              wx.setNavigationBarTitle({
                title: that.data.headerTitle
              })
            }
            that.formatComponentdata();//格式化模板数据
          } else {
            console.log(res.data)
          }
        },
        complete: function () {
          wx.hideLoading();
          wx.stopPullDownRefresh();
        }
      });
    },
    requestVrurl: function () {
      var that = this;
      this.videoContext = wx.createVideoContext('myVideo');
      wx.request({
        url: app.globalData.requestUrl,
        data: {
          map: 'applet_promotional_video'
        },
        success: function (res) {
          console.log(res.data);
          if (res.data.ec == 200) {
            var showPlaybtn = false;
            if (res.data.data.url != '') {
              showPlaybtn = true;
            }
            that.setData({
              videoInfo: res.data.data,
              showPlaybtn: showPlaybtn,
              vrurl: res.data.data.vrurl,
              vrShareTitle: res.data.data.vrShareTitle,
              vrShareCover: res.data.data.vrShareCover
            })
          } else {
            that.setData({
              showPlaybtn: false
            })
          }
        },
        complete: function () {
          wx.stopPullDownRefresh();
        }
      });
    },
    // 打开搜索
    toSearchpage: function () {
      wx.navigateTo({
        url: '/pages/searchList/searchList',
      })
    },
    toInformation: function () {
      wx.navigateTo({
        url: '/pages/informationPage/informationPage',
      })
    },
    seckillIndex: function () {
      wx.navigateTo({
        url: '/pages/seckillPageShow/seckillPageShow',
      })
    },
    //秒杀tab选择
    chooseSkillTab: function (e) {
      var that = this;
      var componentData = that.data.componentData;
      var tabIndex = e.currentTarget.dataset.tabindex;
      var componIndex = e.currentTarget.dataset.componindex;
      that.setData({
        [`componentData[${componIndex}].curSort`]: tabIndex
      })
    },
    goodDetail: function (e) {
      var goodId = e.currentTarget.dataset.id;
      var limitId = e.currentTarget.dataset.laid
      if (goodId){
        wx.navigateTo({
          url: '/pages/goodDetail/goodDetail?id=' + goodId + '&laid=' + limitId
        })
      }
    },
    groupDetail: function (e) {
      var goodId = e.currentTarget.dataset.id;
      var status = e.currentTarget.dataset.status;
      // if (status==3){return;}
      if(goodId){
        wx.navigateTo({
          url: '/pages/groupGoodDetail/groupGoodDetail?goodid=' + goodId
        })
      }
    },
    bargainDetail: function (e) {//砍价商品详情
      var that = this;
      var id = e.currentTarget.dataset.id;
      var status = e.currentTarget.dataset.status;
      // if (status == 2) { return; }
      if(id){
        wx.navigateTo({
          url: '/subpages/bargainGoodDetail/bargainGoodDetail?id=' + id
        })
      }
      
    },
    tojfgoodDetail: function (e) {
      var id = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: '/subpages/jfGoodDetail/jfGoodDetail?id=' + id
      })
    },
    toMoreGoods:function(e){
      var id = e.target.dataset.id;
      var title = e.target.dataset.title;
      wx.navigateTo({
        url: '/pages/allgoodsPage/allgoodsPage?oneid=""&secondid='+id+'&title='+title
      })
    },
    groupIndex:function(){
      wx.navigateTo({
        url: '/pages/groupIndexPage/groupIndexPage',
      })
    },
    bargainIndex: function () {
      wx.navigateTo({
        url: '/subpages/bargainIndexPage/bargainIndexPage',
      })
    },
    seckillIndex: function () {
      wx.navigateTo({
        url: '/pages/seckillPageShow/seckillPageShow',
      })
    },
    myjfshop: function () {//积分商城
      wx.navigateTo({
        url: '/subpages/integralShop/integralShop'
      })
    },
    // 打开地图
    openMap: function (e) {
      var latitude = e.currentTarget.dataset.lat;
      var longitude = e.currentTarget.dataset.lng;
      var address = e.currentTarget.dataset.address;
      var name = e.currentTarget.dataset.name;
      wx.openLocation({
        latitude: Number(latitude),
        longitude: Number(longitude),
        name: name,
        address: address,
        scale: 18
      })
    },
    toInfoDetail: function (e) {
      var id = e.currentTarget.dataset.id;
      if(id){
        wx.navigateTo({
          url: '/pages/informationDetail/informationDetail?id=' + id
        })
      }
    },
    // VR视图
    toWebview: function (e) {
      var that = this;
      var vrurl = e.currentTarget.dataset.vrurl;
      var cover = e.currentTarget.dataset.cover;
      var title = e.currentTarget.dataset.title;
      var vrInfo = {
        vrurl: vrurl,
        cover: cover ? cover : '',
        title: title ? title : ''
      }
      wx.setStorage({
        key: 'webviewUrl',
        data: vrInfo,
        success: function () {
          wx.navigateTo({
            url: '/pages/commonView/commonView',
          })
        }
      })
    },
    //快捷导航跳转
    openFenleiLink: function (e) {
      var that = this;
      var type = e.currentTarget.dataset.type;
      console.log(type);
      if (type == 'index') {
        wx.reLaunch({
          url: indexUrl
        })
      } else if (type == '102') {
        var telphone = app.globalData.telphone ? app.globalData.telphone:'';
        var mobile = e.currentTarget.dataset.mobile;
        mobile = mobile ? mobile : telphone;
        if (mobile) {
          app.makeCallphone(mobile);
        }else{
          app.errorTip(that, "暂未获取到电话", 2000);
        }
      } else if (type == '105') {
        that._requestSign();
      } else if (type == '103') {
        wx.navigateTo({
          url: '/pages/sharepage/sharepage'
        })
      } else if (type == '3') {
        var url = e.currentTarget.dataset.url;
        var vrInfo = {
          vrurl: url
        }
        wx.setStorage({
          key: 'webviewUrl',
          data: vrInfo,
          success: function () {
            wx.navigateTo({
              url: '/pages/commonView/commonView',
            })
          }
        })
      } else if (type != '106' && type != '101'){
        var url = e.currentTarget.dataset.url;
        if(url){
          console.log(url);
          wx.navigateTo({
            url: url
          })
        }
      }
    },
    _requestSign: function () {
      var that = this;
      wx.request({
        url: app.globalData.requestUrl,
        data: {
          map: 'applet_sign_get_point'
        },
        success: function (res) {
          console.log(res.data);
          if (res.data.ec == 200) {
            app.errorTip(that, res.data.data.msg, 2000);
          } else {
            app.errorTip(that, res.data.em, 2000);
          }
        },
        complete: function () {
        }
      });
    },
    getCoupon: function (e) {
      var that = this;
      var curId = e.currentTarget.dataset.id;
      that.setData({
        curId: curId
      })
      app.getSubId(that, 'applet_coupon_receive', 'toGetCoupon');
    },
    // 领取优惠券跳转
    toGetCoupon: function (e) {
      var that = this;
      var id = that.data.curId;
      console.log(id);
      wx.showLoading({
        title: '领取中',
        mask: true
      })
      wx.request({
        url: app.globalData.requestUrl,
        data: {
          map: 'applet_coupon_receive',
          cid: id
        },
        success: function (res) {
          console.log(res.data);
          if (res.data.ec == 200) {
            app.errorTip(that, res.data.data.msg, 2000);
            console.log(that.data.errorTip);
          } else {
            app.errorTip(that, res.data.em, 2000);
          }
        },
        complete: function () {
          wx.hideLoading();
        }
      })

    },
    //一级分类切换
    toggleChange: function (e) {
      var that = this;
      var componentData = that.data.componentData;
      var categoryId = e.currentTarget.dataset.categoryid;
      var componIndex = e.currentTarget.dataset.componindex;
      var name = e.currentTarget.dataset.name;
      console.log(componIndex)
      that.setData({
        [`componentData[${componIndex}].categoryId`]: categoryId,
        toViewCategoryId: 'category' + categoryId + componIndex,
        curGoodFl: '',
      });
      if (categoryId){
        wx.navigateTo({
          url: '/pages/allgoodsPage/allgoodsPage?secondid='+categoryId+'&title='+name,
        })
      }
    },
    //打开弹窗
    openModel: function (e) {
      var that = this;
      var componIndex = e.currentTarget.dataset.componindex;
      var componentData = that.data.componentData;
      that.setData({
        [`componentData[${componIndex}].modelShow`]: true,
      })
    },
    // 优惠券分享领取
    shareGet(e){
      console.log(e);
      var componentData = this.data.componentData;
      console.log('首页信息', componentData);
      var index1=e.currentTarget.dataset.index1;
      var index2 = e.currentTarget.dataset.index2;
      componentData[index1].couponData[index2].needShare=0;
      this.setData({
        componentData: componentData
      })
    },
    //关闭弹窗
    closeModel: function (e) {
      var that = this;
      var componIndex = e.currentTarget.dataset.componindex;
      var componentData = that.data.componentData;
      that.setData({
        [`componentData[${componIndex}].modelShow`]: false
      })
    },

    addminusCart: function (e) {
      var that = this;
      var curgood = e.currentTarget.dataset.curgood;
      var smallNum = curgood.smallNum;
      var buyNum = 1;
      if(smallNum!=undefined)
        buyNum = parseInt(smallNum);
      that.setData({
        curgood: curgood,
        buyNumber: buyNum,
        curImgformat: '',
        chooseGuige: {
          stock: curgood.stock
        },
        isShowFormat: true
      })
    },
    hideFormat: function () {
      var that = this;
      that.setData({
        isShowFormat: false
      })
    },
    stoptouchmove: function (e) {
      console.log(e);
    },
    //单张图片预览
    singlePeiviewImg: function (e) {
      var curimg = e.currentTarget.dataset.curimg;
      var imgs = new Array(e.currentTarget.dataset.imgs);
      wx.previewImage({
        current: curimg, // 当前显示图片的http链接
        urls: imgs // 需要预览的图片http链接列表
      })
    },
    chooseGuige: function (e) {
      var that = this;
      var findex = e.target.dataset.findex;
      var index = e.target.dataset.index;
      var curgood = that.data.curgood;
      if (findex == 0) {
        var curImgformat = curgood.formatList[0].value[index];
        that.setData({
          curImgformat: curImgformat
        })
      }
      var checkFormat = [];
      for (var i = 0; i < curgood.formatList[findex].value.length; i++) {
        curgood.formatList[findex].value[i].checked = false;
      }
      curgood.formatList[findex].value[index].checked = true;
      for (var i = 0; i < curgood.formatList.length; i++) {
        for (var j = 0; j < curgood.formatList[i].value.length; j++) {
          if (curgood.formatList[i].value[j].checked) {
            checkFormat.push(curgood.formatList[i].value[j]);
          }
        }
      }
      that.setData({
        curgood: curgood,
        checkFormat: checkFormat
      })
      if (checkFormat.length == curgood.formatList.length) {
        var formatName = '';
        for (var i = 0; i < checkFormat.length; i++) {
          formatName += checkFormat[i].name;
        }
        console.log(formatName);
        var chooseGuige = curgood.formatValue[formatName];
        chooseGuige.formatName = formatName;
        chooseGuige.formatName = formatName;
        console.log(chooseGuige);
        that.setData({
          chooseGuige: chooseGuige
        })
      }
    },
    changeNum: function (e) {
      var that = this;
      var type = e.currentTarget.dataset.type;
      var buyNum = parseInt(that.data.buyNumber);
      var stock = parseInt(that.data.chooseGuige.stock);
      var purchase = parseInt(that.data.curgood.purchase);
      var disabled = e.currentTarget.dataset.disable;
      if (disabled) return;
      if (type == 'add') {
        if (stock == 0) {
          app.errorTip(that, '商品库存不足', 2000);
        }
        if (buyNum < stock) {
          if (buyNum < purchase) {
            buyNum++;
          } else {
            app.errorTip(that, '超出限购数量', 2000);
          }
        } else {
          buyNum = stock;
        }
      } else {
        var smallNum = that.data.curgood.smallNum > 1 ? that.data.curgood.smallNum : 1;
        if (buyNum > smallNum) {
          buyNum--;
        } else {
          buyNum = smallNum;
        }
      }

      that.setData({
        buyNumber: buyNum
      })
    },
    numChange: function (e) {
      var that = this;
      var stock = that.data.chooseGuige.stock;
      var val = e.detail.value;
      val = val.replace(/\D/g, '');
      if ((parseInt(val)) > parseInt(stock)) {
        that.setData({
          buyNumber: stock
        })
      } else {
        that.setData({
          buyNumber: val
        })
      }
    },
    confirmAddcart: function (e) {
      var that = this;
      var curgoodCart = that.data.curgoodCart;
      var gid = e.currentTarget.dataset.gid;
      var gfid = that.data.chooseGuige.id;
      var num = parseInt(that.data.buyNumber);
      var isFormat = that.data.curgood.hasFormat;
      var stock = parseInt(that.data.chooseGuige.stock);
      var data = {
        map: 'applet_add_cart',
        gid: gid,
        gfid: gfid,
        num: num,
        add: 1
      }
      if (isFormat && !gfid) {
        app.errorTip(that, '请选择商品规格！', 2000);
        return;
      }
      if (!data.num || data.num <= 0) {
        app.errorTip(that, '请输入正确的商品数量', 2000);
        return;
      }
      console.log("库存数量" + stock);
      console.log("商品数量" + data.num);
      if (data.num > stock) {
        app.errorTip(that, '商品数量超出库存', 2000);
        return;
      }
      console.log(data);
      wx.request({
        url: app.globalData.requestUrl,
        data: data,
        success: function (res) {
          console.log(res.data);
          if (res.data.ec == 200) {
            that.setData({
              isShowFormat: false,
              cartNum: res.data.data.cartNum
            })
            that.hideFormat();
            app.errorTip(that, '已成功加入购物车', 2000);
            app.globalData.requestCartNum = res.data.data.cartNum;
            app.setCartnum();//更新购物车数量
          } else {
            app.errorTip(that, res.data.em, 2000);
          }
        },
        complete: function () {
        }
      });
    },

    formatComponentdata: function () {
      let that = this;
      let componentData = that.data.componentData;
      console.log('自定义模板数据', componentData);
      for (let i = 0; i < componentData.length; i++) {
        let type = componentData[i].type;
        for (let m in componentData[i].style) {
          if (m == 'width' && (type == 'fenlei' || type == 'search')) {
            componentData[i].style[m] = componentData[i].style[m] + '%';
          }
          if (componentData[i].style[m] > 0) {
            componentData[i].style[m] = componentData[i].style[m] * 2 + 'rpx';
          }
        }
        if (type == 'search') {
          for (let m in componentData[i].searchArea) {
            if (componentData[i].searchArea[m] > 0) {
              componentData[i].searchArea[m] = componentData[i].searchArea[m] * 2 + 'rpx';
            }
          }
        }
        if (type == 'slide') {
          if (componentData[i].borderRadius > 0) {
            componentData[i].borderRadius = componentData[i].borderRadius * 2 + 'rpx';
          }
        }
        if (type == 'fenlei') {
          if (componentData[i].iconRadius > 0) {
            componentData[i].iconRadius = componentData[i].iconRadius * 2 + 'rpx';
          }
          var navNumber = componentData[i].navNumber * 2;
          var flitems = componentData[i].flitems;
          var flPageitems = app.splitArrData(flitems, navNumber);
          componentData[i].flPageitems = flPageitems;
        }
        if (type == 'notice') {
          var noticeTxt = componentData[i].noticeTxt;
          var noticeTxtPage = app.splitArrData(noticeTxt, 2);
          componentData[i].noticeTxtPage = noticeTxtPage;
        }
        if (type == 'image') {
          for (let m in componentData[i].imageStyle) {
            if (componentData[i].imageStyle[m] > 0) {
              componentData[i].imageStyle[m] = componentData[i].imageStyle[m] * 2 + 'rpx';
            }
          }
        }
        if (type == 'video') {
          componentData[i].videosrc = componentData[i].videolink;
        }
        if (type == 'button') {
          for (let m in componentData[i].buttonStyle) {
            if (componentData[i].buttonStyle[m] > 0) {
              componentData[i].buttonStyle[m] = componentData[i].buttonStyle[m] * 2 + 'rpx';
            }
          }
        }
        if (type == 'space') {
          for (let m in componentData[i].spaceStyle) {
            if (componentData[i].spaceStyle[m] > 0) {
              componentData[i].spaceStyle[m] = componentData[i].spaceStyle[m] * 2 + 'rpx';
            }
          }
        }
        if (type == 'goodlist' || type == 'group' || type == 'seckill' || type == 'bargain' || type == 'points') {
          for (let m in componentData[i].titleStyle) {
            if (componentData[i].titleStyle[m] > 0) {
              componentData[i].titleStyle[m] = componentData[i].titleStyle[m] * 2 + 'rpx';
            }
          }
          for (let n in componentData[i].priceStyle) {
            if (componentData[i].priceStyle[n] > 0) {
              componentData[i].priceStyle[n] = componentData[i].priceStyle[n] * 2 + 'rpx';
            }
          }
        }
        if (type == 'pictxt' || type == 'recommendList') {
          for (let m in componentData[i].titleCss) {
            if (componentData[i].titleCss[m] > 0) {
              componentData[i].titleCss[m] = componentData[i].titleCss[m] * 2 + 'rpx';
            }
          }
          for (let n in componentData[i].imageStyle) {
            if (componentData[i].imageStyle[n] > 0) {
              componentData[i].imageStyle[n] = componentData[i].imageStyle[n] * 2 + 'rpx';
            }
          }
        }
        if (type == 'coupon') {
          if (componentData[i].limitStyle.fontSize > 0) {
            componentData[i].limitStyle.fontSize = componentData[i].limitStyle.fontSize * 2 + 'rpx';
          }
          if (componentData[i].valueStyle.fontSize > 0) {
            componentData[i].valueStyle.fontSize = componentData[i].valueStyle.fontSize * 2 + 'rpx';
          }
        }
        if (type == 'window') {
          if (componentData[i].imageStyle.borderRadius > 0) {
            componentData[i].imageStyle.borderRadius = componentData[i].imageStyle.borderRadius * 2 + 'rpx';
          }
          if (componentData[i].imageStyle.padding > 0) {
            componentData[i].imageStyle.padding = componentData[i].imageStyle.padding * 2 + 'rpx';
          }
        }
        if (componentData[i].requestDataCfg) {
          wx.request({
            url: app.globalData.requestUrl + '&' + componentData[i].requestDataCfg['params'],
            data: {
              map: componentData[i].requestDataCfg['api']
            },
            success: function (res) {
              let field = componentData[i].requestDataCfg['dataType'];
              that.setData({
                [`componentData[${i}].${field}`]: res.data.data
              })
              if (type == 'cateGoods') {
                that.setData({
                  [`componentData[${i}].goodsList[0].goods`]: res.data.data,
                  [`componentData[${i}].goodsList[0].hasGoods`]: true
                })
              }
              if (type == 'live'&&res.data.ec==200) { //直播组件信息
                if (res.data.data.length > 0) {
                  livePlayer = requirePlugin('live-player-plugin');
                  console.log('直播列表',res.data.data);
                  for (let j = 0; j < res.data.data.length; j++) {
                    livePlayer.getLiveStatus({ room_id: res.data.data[j].room_id }).then(res1 => {
                      console.log(res1);
                      if(res.data.data[j].live_status != res1.liveStatus){
                        that.setData({
                          [`componentData[${i}].liveList[${j}].live_status`]: res1.liveStatus
                        })
                        app.updateLiveStatus(res.data.data[j].room_id,res1.liveStatus)
                      }
                    }).catch(err => {
                      console.log(err)
                    })

                  }
                }
              }
            },
          });
        }
      }
      that.setData({
        componentData: componentData
      })
      console.log(componentData);
    },
  }
})